package core

import (
	"github.com/BurntSushi/toml"
	"github.com/garyburd/redigo/redis"
	"github.com/ngaut/log"
	"time"
	"sync"
	"global/model"
	"os"
)

// 上下文
type Context struct {
	startTime 		time.Time
	Configuration
	mu 				sync.Mutex
	RedisPool 		map[string]*redis.Pool
}

func NewContext() *Context {
	return &Context{
		RedisPool: 	make(map[string]*redis.Pool),
	}
}

// 是否是调试模式
func (c *Context) IsDebug() bool {
	return c.Configuration.App.Debug
}

// 获取配置
func (c *Context) AccountConfig() (string) {
	var account accountConfig
	if c.IsDebug() {
		account = c.Configuration.Accounts["sandbox"]
	} else {
		account = c.Configuration.Accounts["production"]
	}
	return account.Key
}

func (c *Context) setCoinfigure(configuration Configuration) {
	c.Configuration = configuration
}

// 初始化
func (c *Context) Bootstrap(configFile, symbol string) *Context {
	// config
	c.setCoinfigure(loadConfiguration(configFile))

	c.configLogs(symbol)

	// redis
	c.registRedis()

	// db
	c.db()

	return c
}

func (c *Context) configLogs(symbol string)  {
	// log
	baseConfig := c.Log["base"] // .Setting()
	v, ok := c.Log[symbol];
	if !ok {
		println("Please check config log setting, symbol:", symbol)
		os.Exit(1)
	}

	if v.Dir != "" {
		baseConfig.Dir = v.Dir
	}
	if v.File != "" {
		baseConfig.File = v.File
	}
	if v.Level != "" {
		baseConfig.Level = v.Level
	}
	if v.Rotate != "" {
		baseConfig.Level = v.Rotate
	}
	baseConfig.Setting()
}

func (c *Context) Initialize() {
	c.startTime = time.Now()
}

func (c *Context) db() {
	if conf, ok := c.Db["main"]; ok {
		logOn, file := conf.GetDBLogConfig()
		model.InitMainDB(conf.FormatDBConnection(), logOn, file)
		log.Infof("main database configuration ok.")
	} else {
		log.Errorf("check main database config.")
	}
}

func (c *Context) registRedis() {
	for key, conf := range c.Redis {
		pool := conf.redisPool()
		if pool == nil {
			panic("redis init error")
		}
		c.RedisPool[key] = conf.redisPool()
	}

	if len(c.RedisPool) == 0 {
		panic("redis init error, please check config.")
	}
}

func (c *Context) GetBaseRedis() *redis.Pool {
	p, ok := c.RedisPool["base"]
	if !ok {
		panic("get redis pool of ote failed")
	}
	return p
}

// 图片地址
func (c *Context) GetImgUrl() string {
	return c.Configuration.App.ImgUrl
}

func loadConfiguration(configFile string) Configuration {
	configuration := newConfiguration()
	_, err := toml.DecodeFile(configFile, &configuration)
	if err != nil {
		panic(err.Error())
	}
	return configuration
}
